<?php 

/**
 * Class Request
 * <example>
 *  if ( !DM_Request::isAjax() ) {
 *		DM_Request::redirect('http://yandex.ru');
 *	}
 * </example>
 */

class DM_Request {
	protected static $rewriteList = array();
	protected static $params;
	protected static $_isPost = false;
	protected static $_isAjax = false;
		
	protected function __construct() {		
		
	}
	
	public static function init() {
		self::$_isPost = is_array($_POST) && count($_POST);
		self::$_isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(trim($_SERVER['HTTP_X_REQUESTED_WITH'])) == 'xmlhttprequest';
	}
	
	public static function isPost() {		
		return self::$_isPost;
	}
	
	public static function get( $paramName ) {
		if ( isset(self::$params[ $paramName ]) ) {
			return self::$params[ $paramName ];
		}
		return null;
	}
	
	public static function route() {
		if ( !count(self::$rewriteList) ) {
			DM_Loader::load('Request/Router');
			self::$rewriteList[] = new DM_Request_Router();
		}
		
		$result;
		foreach( self::$rewriteList as $router ) {
			if ( $result = $router->assemble() ) {				
				self::$params = isset($result['params'])?$result['params']:null;
				$result['params'] = &self::$params;
				return $result;
			}
		}
		return null;
	}
	
	public static function addRewriteRule( $rule ) {
		if ( $rule instanceof DM_Request_IRouter ) {
			self::$rewriteList[] = $rule;
		} elseif ( is_string($rule) ) {
			DM_Loader::load('Request/RegexRouter');
			self::$rewriteList[] = new DM_Request_RegexRouter( $rule );
		}
	}
	
	public static function redirect( $url ) {
		header('Location: '.$url);
		die();
	}
	
	public static function isAjax() {
		return self::$_isAjax;
	}
}

?>